package cn.iocoder.an.module.business.utils.strategy;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;

// 3. 策略管理器
@Service
public class ActionDispatcher {
    private final Map<String, ActionStrategy> strategyMap = new HashMap<>();

    // 构造时自动注入所有策略
    public ActionDispatcher(List<ActionStrategy> strategies,
                            ApplicationContext context) {
        String[] beanNames = context.getBeanNamesForType(ActionStrategy.class);
        for (String name : beanNames) {
            ActionStrategy strategy = (ActionStrategy) context.getBean(name);
            // 使用 Bean 名称作为 key（或自定义注解）
            strategyMap.put(name, strategy);
        }
    }

    public Object execute(String methodName, Map<String, Object> params) {
        ActionStrategy strategy = strategyMap.get(methodName);
        if (strategy == null) {
            throw exception("方法不存在: " + methodName);
        }
        return strategy.execute(params);
    }
}